const router = require('express').Router()
const path = require('path')
const {
  getUserList,
  getUserInfo,
  insertUser,
  queryUserById,
  selectUserByUsernamePassword,
  updateUserAvatar
} = require('../model/userModel')
const { createSuccess, createFail } = require('../utils/result')
const { userIsExist, isLogin } = require('../middleware/userMiddleWare')
const multer = require('multer')
const storage = multer.diskStorage({
  destination(req, file, cb) {
    var rootDir = path.resolve(__dirname, '../../static/uploads')
    cb(null, rootDir)
  },
  filename(req, file, cb) {
    const ext = path.extname(file.originalname)
    const filename = Date.now() + ext
    cb(null, filename)
  }
})
const upload = multer({ storage })

// 获取用户列表
router.get('/list', isLogin, (req, res, next) => {
  getUserList().then((results) => {
    const users = results.map(
      ({ id, username, gender, role, user_status, create_time, avatar }) => ({
        id,
        username,
        gender,
        role,
        user_status,
        create_time,
        avatar
      })
    )
    res.json(createSuccess(users))
  }, next)
})

// 根据 id 获取用户信息
router.post('/info', isLogin, (req, res, next) => {
  const { id } = req.body
  if (!id) {
    res.json(createFail('id不能为空'))
  }
  getUserInfo(id).then((results) => {
    const [user] = results
    if (user) {
      const { id, username, role, gender, user_status, create_time, avatar } =
        user
      res.json(
        createSuccess({
          id,
          username,
          role,
          gender,
          user_status,
          create_time,
          avatar
        })
      )
    } else {
      res.json(createFail('用户不存在'))
    }
  }, next)
})

// 用户注册
router.post('/register', userIsExist, (req, res, next) => {
  const { username, password } = req.body
  insertUser(username, password).then((results) => {
    const insertId = results.insertId
    return queryUserById(insertId).then((results) => {
      const [user] = results
      const { id, username, gender, user_status, create_time, avatar } = user
      res.json(
        createSuccess({
          id,
          username,
          gender,
          user_status,
          create_time,
          avatar
        })
      )
    }, next)
  }, next)
})

// 用户登录
router.post('/login', (req, res, next) => {
  const { username, password } = req.body
  selectUserByUsernamePassword(username, password).then((results) => {
    if (results.length > 0) {
      const user = results[0]
      req.session.user = user
      res.json(createSuccess(user, '登录成功'))
    } else {
      res.json(createFail('用户名或密码错误'))
    }
  }, next)
})

// 用户退出
router.get('/logout', (req, res) => {
  req.session.destroy()
  res.json(createSuccess())
})

// 图片上传
router.post('/avatar', isLogin, upload.single('avatar'), (req, res, next) => {
  const url = `/uploads/${req.file.filename}`
  const id = req.session.user.id
  updateUserAvatar(id, url).then((results) => {
    if (results.affectedRows === 1) {
      return queryUserById(id).then((results) => {
        const [user] = results
        const { id, username, gender, user_status, create_time, avatar } = user
        res.json(
          createSuccess({
            id,
            username,
            gender,
            user_status,
            create_time,
            avatar
          })
        )
      }, next)
    }
  }, next)
})

module.exports = router
